use anyhow::{Context, Result};
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::PathBuf;

#[derive(Debug, Deserialize, Serialize)]
struct UserRepo {
    owner: String,
    repo: String,
}

#[derive(Debug, Deserialize, Serialize)]
struct Namespace {
    id: i64,
    name: String,
    path: String,
    html_url: String,
}

#[derive(Debug, Deserialize, Serialize)]
struct Creator {
    id: String,
    username: String,
    arts_id: String,
    nickname: Option<String>, // 使用 Option 来处理可能为 null 或空字符串的字段
    email: String,
    photo: String,
}

#[derive(Debug, Deserialize, Serialize)]
struct UserRepoResp {
    id: i64,
    full_name: String,
    human_name: String,
    url: String,
    namespace: Namespace,
    path: String,
    name: String,
    description: Option<String>, // 使用 Option 来处理可能为 null 的字段
    private: bool,
    public: bool,
    status: String,
    ssh_url_to_repo: String,
    http_url_to_repo: String,
    web_url: String,
    readme_url: Option<String>, // 同样使用 Option
    created_at: String,     // 这里假设你能够将字符串解析为 SystemTime
    updated_at: String,     // 同上
    creator: Creator,
    homepage: Option<String>,
}


pub const GITCODE_CMD_CONFIG: &'static str = ".gitcode-cmd-config";
fn home_dir() -> Option<PathBuf> {
    // 使用 std::env::home_dir. 它的 bug 是，IMO，非常小的极端情况。
    #![allow(deprecated)]
    std::env::home_dir()
}

fn gitcode_cmd_config_contents() -> Option<Vec<u8>> {
    let home = match home_dir() {
        None => return None,
        Some(home) => home,
    };
    let mut file = match File::open(home.join(GITCODE_CMD_CONFIG)) {
        Err(_) => return None,
        Ok(file) => BufReader::new(file),
    };
    let mut contents = vec![];
    file.read_to_end(&mut contents).ok().map(|_| contents)
}

fn token() -> Result<String> {
    match std::env::var_os("GITCODE_PRIVATE_TOKEN") {
        None => {
            let gitcode_cmd_config = gitcode_cmd_config_contents();
            match gitcode_cmd_config {
                Some(config_content) => {
                    String::from_utf8(config_content).with_context(|| format!("解析配置文件 {GITCODE_CMD_CONFIG} 错误"))
                }
                None => panic!("未找到 gitcode private token 配置")
            }
        }
        Some(token) => {
            // token.into_string().with_context(|| "gitcode private token 错误")
            Ok(token.to_string_lossy().into_owned())
        }
    }
}


fn main() -> Result<()> {
    // 创建一个新的 Client 实例
    let client = Client::new();

    let token = token()?;
    let owner = "gitcode-repo";
    let repo = "gitcode-open-api";
    // GitHub API 的仓库搜索 URL
    let url = format!("https://api.gitcode.com/api/v5/repos/{owner}/{repo}?access_token={token}");

    // 发送 GET 请求并获取响应
    let response = client.get(url).send()?;

    // 检查响应状态码
    if response.status().is_success() {
        // 将响应体解析为 ReposResponse 结构
        let repo: UserRepoResp = response.json()?;
        println!("ID: {}, Name: {}, Full Name: {}", repo.id, repo.name, repo.full_name);
    } else {
        // 处理非成功状态码
        eprintln!("Error: {}", response.status());
        eprintln!("Body: {}", response.text()?);
    }

    Ok(())
}
